import requests
import os
import argparse
import json
import cams
import time
import cv2
import numpy as np
import svar

osdk=svar.load('svar_osdk')

env=osdk.LinuxSetup(True)
vehicle = env.getVehicle()

# start rtmv publish
options={}
options["camera_position"]=osdk.OSDK_CAMERA_POSITION_NO_1
options["playload_index"]=osdk.PAYLOAD_INDEX_0
options["enable_rtmv"]=False
node=osdk.VehicleNode(vehicle,options)

# prepare task
parameters={}
#parameters["planar.post_processing"]=1
parameters["planar.incremental"]=1
parameters["map2dfusion.auto_zoom"]=1
parameters["map2dfusion.cache_size"]=400
cameras = cams.cameras
server='http://192.168.1.191:1024'
task={"task":"online_planar","parameters":parameters,"dataset":{"type":"images_stream","cameras":cameras,"images":[]}}
headers = {'Content-Type': 'application/json;charset=UTF-8'}
r = requests.request("post",server+"/task",json=task,headers=headers)
print("task created with response",r.text)
taskid=r.json()['taskid']

def post_image(taskid,imgfile):
  taskjson=json.dumps({"image":imgfile})
  jsonfile = os.path.splitext(os.path.split(imgfile)[1])[0]+'.json'
  files={
      "f.json" : (jsonfile,taskjson.encode()),"f.jpg" : open(imgfile, "rb")
     }
  r = requests.post(server+"/task/"+ taskid+"/frame", None, files=files)
  print(r.text)

# start images fetching
downloaded={}
savefolder='.'
is_first=False

while(True):
  vehicle.cameraManager.setModeSync(osdk.PAYLOAD_INDEX_0,osdk.MEDIA_DOWNLOAD,2)
  vehicle.cameraManager.obtainDownloadRightSync(osdk.PAYLOAD_INDEX_0,True,2)

  file_list=vehicle.cameraManager.reqFileList(osdk.PAYLOAD_INDEX_0)

  media=file_list.media
  print("there are ",len(media),"files")

  for m in media:
    if m.fileName.find('WIDE') < 0:
      continue
    if m.fileName.find('198000000') > 0:
      print("abort",m)
      continue
    file_path=os.path.join(savefolder,m.fileName)

    if downloaded.get(m.fileIndex) != None:
      print("abort",m.fileName)
      continue

    if os.path.exists(file_path):
      continue
    if is_first:
      downloaded[m.fileIndex]=m
      continue
    print("reqesting file",file_path,"id",m.fileIndex)
    ret=vehicle.cameraManager.reqFileData(osdk.PAYLOAD_INDEX_0,m.fileIndex,file_path)
    print("reqest finished with code:",ret)
    if ret !=0:
      osdk.ErrorCode.printErrorCodeMsg(ret)
      break
    post_image(taskid,file_path)
  
  if len(media) > 0:
    is_first=False

  time.sleep(3)

r = requests.request("post",server+"/task/"+ taskid+"/frame",json={},headers=headers)
print(r.text)
   
while True:
  time.sleep(1)
  status= get_status(taskid)
  if status["status"] == 'finished':
    exit(0)
  print(status)
